package com.dreamstations.changshads.util;

import java.util.IdentityHashMap;
import java.util.Map;

/**
 * Created by QYH on 2016/6/3.
 */

public class DSRequest {
    private static final String SERVER_ADDR = "http://ds.hnicp.cn/NewParty/AppAction/";
    public static final String SERVER_BASE1 = "http://ds.hnicp.cn";

    private String type, url;
    private Map<String, String> params;
    private int cacheType= DSUtils.NETWORK_ELSE_CACHED;
    private Object tag;

    public Object getTag() {
        return tag;
    }

    public DSRequest setTag(Object tag) {
        this.tag = tag;
        return this;
    }

    public @RequestType
    String getType() {
        return type;
    }

    public int getCacheType() {
        return cacheType;
    }

    public String getUrl() {
        return url;
    }

    public DSRequest cacheType(int cacheType) {
        this.cacheType = cacheType;
        return this;
    }

    public DSRequest type(@RequestType String type) {
        this.type = type;
        return this;
    }


    public DSRequest addParams(String key, String val) {
        if (this.params == null) {
            params = new IdentityHashMap<>();
        }
        params.put(key, val);
        return this;
    }

    private String appendParams(String url, Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        sb.append(url + "?");
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                sb.append(key).append("=").append(params.get(key)).append("&");
            }
        }

        sb = sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public DSRequest build() {
        url = appendParams(SERVER_ADDR + type, params);
        return this;
    }

    public void execute(DSCallback dsCallback){
        DSUtils.getInstance().execute(this,dsCallback);
    }

    public interface DSCallback<T>{
        void onResponse(T result);
        void onFailure(String msg);
    }
}


